<?php
class UsersController extends AppController {
  public $components = array('Session','Auth','Cookie','Captcha' => array(
                                                'rotate' => true
                                            ));
  public $uses=array('User','Order','Ticket','Webhosting');
  public $scaffold = 'admin';
    public function GenerateSalt($n=3)
    {
    	$key = '';
    	$pattern = '1234567890abcdefghijklmnopqrstuvwxyz.,*_-=+';
    	$counter = strlen($pattern)-1;
    	for($i=0; $i<$n; $i++)
    	{
    		$key .= $pattern{rand(0,$counter)};
    	}
    	return $key;
    }

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('add');
    }

    public function login() {
      $this->set('title_for_layout', 'Вход в биллинг');
        if ($this->request->is('post')) {
          if($this->Session->check('User.justregistered'))
          {
            $this->Session->delete('User.justregistered');
          }
          $login=$this->request->data['User']['login'];
          $remember_me=@$this->request->data['User']['remember'];
          $userdata=$this->User->query("SELECT `password`,`salt`,`id`,`role` FROM `users` WHERE `login`='{$login}' LIMIT 1");
          if(count($userdata)>0)
          {
            $salt=$userdata[0]['users']['salt'];
            $passowrd_in_bd=@$userdata[0]['users']['password'];
            $passowrd_from_form=md5(md5($this->request->data['User']['password']) . $salt);
            //echo $passowrd_in_bd.' - '.$passowrd_from_form;
            if($passowrd_in_bd==$passowrd_from_form)
            {
              $this->request->data['User']['password'] = md5(md5($this->request->data['User']['password']) . $salt);
              $this->request->data['User']['id']= $userdata[0]['users']['id'];
              $this->request->data['User']['role']= $userdata[0]['users']['role'];
              $data_for_auth=array('id' => $userdata[0]['users']['id'], 'login'=>$login ,'role' => $userdata[0]['users']['role'],'password' => $this->request->data['User']['password']) ;
                if ($this->Auth->login($data_for_auth)) {
                  if($remember_me==1)
                  {
                      $cookie = array();
                      $cookie=$data_for_auth;
                      //print_r($cookie);
                      $this->Cookie->write('User', $cookie, true, '+2 weeks');
                  }
                  //$this->redirect($this->Auth->redirect());
                  setcookie ("UserAuthInBilling", 'true',null,'/');
                  setcookie ("UserAuthInBillingName", AppController::getUserName($userdata[0]['users']['id']),null,'/');
                  $this->redirect(array('controller'=>'pages','action' => 'index'));
                } else {
                    $this->Session->setFlash(__('Произошла ошибка | Неверный логин или пароль.'));
                    $this->redirect(array('action' => 'login'));
                }
              }
              else {
                    $this->Session->setFlash(__('Произошла ошибка | Неверный логин или пароль.'));
                    $this->redirect(array('action' => 'login'));
              }
          }
          else
          {
            $this->Session->setFlash(__('Произошла ошибка | Неверный логин или пароль.'));
            $this->redirect(array('action' => 'login'));
          }
        }
    }


    public function logout() {
        $this->Cookie->delete('User');
        setcookie("UserAuthInBilling", '',time()-3600,'/');
        setcookie("UserAuthInBillingName", '',time()-3600,'/');
        $this->Auth->logout();
        $this->redirect("http://".$_SERVER['SERVER_NAME']);
    }

    public function index() {
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    public function view($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('user', $this->User->read(null, $id));
    }

    public function forgetpass(){
      $this->autorender = false;
      $this->layout = false;
      $this->set('title_for_layout', 'Восстановление пароля');
      if ($this->request->is('post')) {
        $user_data=$this->request->data['User'];
        $user_login=$user_data['login'];
        $user_email=$user_data['email'];
        if($some_data=$this->User->findByEmailAndLogin($user_email, $user_login))
        {
          //Логин и пароль верны, надо сгенерировать новый пароль для юзера
          //Создаем новый пароль
          $newpass=$this->GenerateSalt(8);// Новый пароль сгенерирован
          //echo $newpass;
          $salt = $this->GenerateSalt();
	      $hashed_password = md5(md5($newpass) . $salt);
          $uid=$some_data['User']['id'];
          $email=$some_data['User']['email'];
          $this->User->query("UPDATE `users` SET  `password`='{$hashed_password}',`salt`='{$salt}' WHERE `id`='{$uid}'");
          //Отправляем письмо юзеру на емаил
          $headers= "MIME-Version: 1.0\r\n";
          $headers .= "Content-type: text/html; charset=utf-8\r\n";
          $headers.="From: support@radioheart.ru\r\n";
          $message="Ваш новый пароль - ".$newpass;
          //mail($email, "Восстановление пароля от биллинга на RadioHeart.ru",$message,$headers);
          $tmp=AppController::send_email($email, "RadioHeart - Восстановление пароля от биллинга",$message,$headers);
          $this->Session->setFlash(__('Восстановление пароля | Новый пароль был отправлен Вам на емаил'));
          $this->redirect(array('action' => 'login'));
        }
      }
      $this->render('forgetpass');

    }

    public function add() {
      $this->autorender = false;
      $this->layout = false;
      $this->set('title_for_layout', 'Шаг 1 - Регистрация');
      $salt=$this->GenerateSalt();
      $this->request->data['User']['salt']=$salt;
      //$this->set('salt', $salt);
        if ($this->request->is('post')) {
          $true_capthca=$this->Session->read('Captcha.code');
          if($this->request->data['User']['password']==$this->request->data['User']['confirmpassword'])
          {
             $tmppass=$this->request->data['User']['password'];
             $tmplogin=$this->request->data['User']['login'];
             $this->request->data['User']['password'] = md5(md5($this->request->data['User']['password']) . $this->request->data['User']['salt']);
             $this->User->setCaptcha($this->Session->read($this->settings['sessionKey']));
             //$this->User->setCaptcha($this->request->data['User']['captcha']);
             //$this->User->set($this->request->data);
             if ($true_capthca==$this->request->data['User']['captcha']) {
               unset($this->request->data['User']['captcha']);
               //сначало надо проверить, что такой логин еще свободен
               $user=$this->User->findByLogin($this->request->data['User']['login']);
               if(!$user)
               {
                  $this->User->create();
                  if ($this->User->save($this->request->data)) {
                      $this->Cookie->write('User.justregistered', 'true',false,120);
                      $this->Cookie->write('justregistered', 'true',false,1200);
                      //$this->Session->setFlash(__('Регистрация успешно завершена | Используйте форму слева для входа в биллинг'));
                      //$this->redirect(array('controller'=>'pages','action' => 'index'));
                      //отправляем юзеру сообщение, о том, что он успешно зарегестрирован в биллинге
                      $user_email=$this->request->data['User']['email'];
                      $headers= "MIME-Version: 1.0\r\n";
                      $headers .= "Content-type: text/html; charset=utf-8\r\n";
                      $headers.="From: support@radioheart.ru\r\n";
                      $message="Поздравляем! Вы успешно зарегистрировались в биллинге компании Radioheart!<br />
                      Ваш логин: $tmplogin <br />
                      Ваш пароль: $tmppass <br />
                      После авторизации вам необходимо сделать новый заказ, оплатить его и дождаться активации.<br />
                      Компания Radioheart искренне рада видеть вас в числе своих клиентов.
                      ";
                      $tmp=AppController::send_email($user_email, "RadioHeart - регистрация пройдена успешно",$message,$headers);
                      //Сразу авторизовываем юзера
                      $userdata=array();
                      $userdata[0]['users']['id']=$this->User->getLastInsertID();
                      $data_for_auth=array('id' => $userdata[0]['users']['id'], 'login'=>$this->request->data['User']['login'] ,'role' => 0,'password' => $this->request->data['User']['password']) ;
                      if ($this->Auth->login($data_for_auth)) {
                        setcookie ("UserAuthInBilling", 'true',null,'/');
                        setcookie ("UserAuthInBillingName", AppController::getUserName($userdata[0]['users']['id']),null,'/');
                        $this->redirect(array('controller'=>'pages','action' => 'index'));
                        }
                  } else {
                      $this->Session->setFlash(__('Произошла ошибка при регистрации. Пожалуйста, попробуйте еще раз.'));
                      $this->redirect(array('action' => 'add'));
                  }
                }
                else
                {
                   $this->request->data['User']['password']='';
                   $this->request->data['User']['confirmpassword']='';
                   $this->request->data['User']['captcha']='';
                   $this->Session->setFlash(__('Данный логин уже занят'));
                }
              }
              else
              {
                $this->request->data['User']['password']='';
                $this->request->data['User']['confirmpassword']='';
                $this->request->data['User']['captcha']='';
                $this->Session->setFlash(__('Не правильно введен код с картинки'));
              }
            }
            else
            {
              $this->request->data['User']['password']='';
              $this->request->data['User']['confirmpassword']='';
              $this->request->data['User']['captcha']='';
              $this->Session->setFlash(__('Пароли не совпадают'));
            }
        }
        $this->render('step1');
    }
     public function captcha()  {
        $this->autoRender = false;
        $this->Captcha->generate();
        //echo "123";
    }

    public function edit($id = null) {
      $userid= $this->Auth->User('id');
      $this->set('title_for_layout', 'Редактирование настроек пользователя');
      $this->set('user_name_sidebar', AppController::getUserName($userid));
      if(!isset($id))
        $id=$this->Auth->User('id');
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $userdata=$this->User->query("SELECT `id`,`login`,`password`,`salt`,`role` FROM `users` WHERE `id`='{$id}' LIMIT 1");
        $salt=$userdata[0]['users']['salt'];
        $passowrd_in_bd=@$userdata[0]['users']['password'];
        $userlogin=@$userdata[0]['users']['login'];
        $id_from_bd=$userdata[0]['users']['id'];
        $user_role=$userdata[0]['users']['role'];
        if($userid!=$id_from_bd)
        {
          if(!AppController::isAuthorized($userid)){
            $this->Session->setFlash(__('У вас нет прав для просмотра этого раздела'));
            $this->redirect(array('controller'=>'pages','action' => 'index'));
          }
        }
        $this->set('salt',$salt);
        $this->set('userlogin',$userlogin);
        $this->set('user_role',$user_role);
        if ($this->request->is('post') || $this->request->is('put')) {
            if($this->request->data['User']['password']==$this->request->data['User']['confirmpassword'])
            {
              //если юзер не обновляет пароль, вставляем тупо пароль из базы
              if($this->request->data['User']['password']=='')
                $this->request->data['User']['password']=$passowrd_in_bd;
              else
                $this->request->data['User']['password'] = md5(md5($this->request->data['User']['password']) . $this->request->data['User']['salt']);
              if ($this->User->save($this->request->data)) {
                  $this->Session->setFlash(__('Настройки успешно сохранены'));
                  $this->redirect(array('action' => 'edit'));
              } else {
                  $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
              }
            }
        } else {
            $this->request->data = $this->User->read(null, $id);
            unset($this->request->data['User']['password']);
        }
    }

    public function delete($id = null) {
        if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->User->delete()) {
            $this->Session->setFlash(__('User deleted'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('User was not deleted'));
        $this->redirect(array('action' => 'index'));
    }
    public function addcredits($howmany=null,$autosubmit=null){
      //if($this->Cookie->read('Order.fromneworders')==1)
      if(isset($autosubmit))
        $this->set('autosubmit',1);
      else
        $this->set('autosubmit',0);
      $userid= $this->Auth->User('id');
      $this->set('title_for_layout', 'Пополнение баланса');
      $this->set('user_name_sidebar', AppController::getUserName($userid));
      $this->set('userid',$userid);
      $query="SELECT * FROM `robokassa` WHERE `id`='1' LIMIT 1";
      $tmp=$this->User->query($query);
      $number=$tmp[0]['robokassa']['number'];
      $number++;
      $query="UPDATE `robokassa` SET `number`='$number' WHERE `id`='1' LIMIT 1";
      $this->User->query($query);
      $user_data=$this->User->findById($userid);
      $user_login=$user_data['User']['login'];
      $this->set('number',$number);
      $this->set('user_login',$user_login);
      if(isset($howmany))
      {
        //делаем поправку на комиссию
        $howmany=file_get_contents("http://radioheart.ru/billing/robokassa.php?sum=".$howmany);
        $howmany=round($howmany,2);
        $this->set('howmany',$howmany);
      }
      else
      {
        $this->set('howmany',1);
      }


        $orders=$this->Order->find('all',array(
                                    'conditions' => array('Order.userid' => $userid),
                                    'order' => array('Order.oplachenodo' => 'asc')));
        $this->set('orders', $orders);
        $webhosting_orders=$this->Webhosting->find('all',array(
                                    'conditions' => array('Webhosting.userid' => $userid),
                                    'order' => array('Webhosting.oplachenodo' => 'asc')));
        $this->set('webhosting_orders', $webhosting_orders);
        $active_orders=0;
        $not_active_orders=0;
        $need_pay_orders=0;
        $all_orders_cost=0;
        $autocontinue_one_of=0;
        //radiohost
        foreach($orders as $order)
        {
          $status=$order['Order']['status'];
          switch($status){
            case '0': $not_active_orders++; break;
            case '1': $need_pay_orders++; break;
            case '2': $active_orders++; break;
          }
          $all_orders_cost+=$order['Order']['cost'];
          if($order['Order']['autocontinue']==1)
            $autocontinue_one_of=1;
        }
        //webhost
        foreach($webhosting_orders as $order)
        {
          $status=$order['Webhosting']['status'];
          $all_orders_cost+=$order['Webhosting']['cost'];
          switch($status){
            case '0': $not_active_orders++; break;
            case '1': $need_pay_orders++; break;
            case '2': $active_orders++; break;
          }
        }
        $this->set('not_active_orders', $not_active_orders);
        $this->set('need_pay_orders', $need_pay_orders);
        $this->set('active_orders', $active_orders);
        $balancedata=AppController::getbalance($userid);
        $this->set('balance_value', $balancedata['balance']);
        $this->set('balance_time', $balancedata['time']);
        $this->set('all_orders_cost', $all_orders_cost);
        $need_money=$balancedata['balance']-$all_orders_cost;
        if($need_money<0)
            $this->set('need_money', -1*$need_money);
        else
            $this->set('need_money', $all_orders_cost);
        $this->set('autocontinue_one_of', $autocontinue_one_of);
    }
    public function paysuccess(){
      //if((@$_COOKIE['radiohost_order_id']>0) or (@$_COOKIE['webhost_order_id'])>0)
      if(isset($_COOKIE['radiohost_order_id']) || isset($_COOKIE['webhost_order_id']))
      {
        //setCookie("tosetup","true",time()+60);
        $this->Session->write('User.tosetup', 'true');
        $this->redirect(array('controller'=>'orders','action' => 'setup/tosetup'));
       //$this->redirect(array('controller'=>'orders','action' => 'confirm'));
      }
      else
      {
        $this->Session->setFlash(__('Операция прошла успешно'));
        $this->redirect(array('action' => 'addcredits'));
      }
    }
    public function payfail(){
      $this->Session->setFlash(__('Вы отказались от оплаты'));
      $this->redirect(array('action' => 'addcredits'));
    }
    public function payresult($userid,$out_summ){
      $query = "SELECT * FROM `balance` WHERE `userid`='$userid'";
      //$sql = mysql_query($query) or die(mysql_error());
      $tmp=$this->User->query($query);
      $count=count($tmp);
      date_default_timezone_set('Europe/Moscow');
      $time=time();
      if($count>0)  //Update
        $query = "UPDATE `balance` SET `balance`=`balance`+$out_summ,`time`='$time' WHERE `userid`='$userid'";
      else //Insert
        $query = "INSERT INTO `balance` (`id`, `userid`, `balance`, `time`) VALUES (NULL, '$userid', '$out_summ', '$time');";
      $this->User->query($query);
      //ОТПРАВКА МНЕ на ящик, что пришла оплата заказа
      $headers= "MIME-Version: 1.0\r\n";
      $headers.= "Content-type: text/html; charset=utf-8\r\n";
      $headers.="From: sale@radioheart.ru\r\n";
      $message="Юзер ".AppController::getUserLogin($userid)." пополнил баланс.";
      mail("germes.07@bk.ru", "RadioHeart - качественный радио хостинг",$message,$headers);
    }

}


?>